/*******************************************************************************
 * This file is part of blueprint4j www.blueprint4j.org.
 * 
 *     blueprint4j is free software: you can redistribute it and/or modify
 *     it under the terms of the GNU Lesser General Public License as published by
 *     the Free Software Foundation, either version 3 of the License, or
 *     (at your option) any later version.
 * 
 *     blueprint4j is distributed in the hope that it will be useful,
 *     but WITHOUT ANY WARRANTY; without even the implied warranty of
 *     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *     GNU Lesser General Public License for more details.
 * 
 *     You should have received a copy of the GNU Lesser General Public License
 *     along with blueprint4j. If not, see <http://www.gnu.org/licenses/>.
 ******************************************************************************/
package blueprint4j.db;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.sql.SQLException;

import blueprint4j.utils.ByteM;

public class FieldFile extends FieldBlob {
	private static final long serialVersionUID = 1L;

	/**
	 * public Field( Blob p_name, Blob p_description, boolean p_key_field
	 *
	 * Name: Name of field -> equivalent to table.field_name
	 * Description: Description of field
	 * key_field: Is this field a key field in the table (index field)
	 */
	public FieldFile( String p_name, int p_field_type ,String p_description,Entity entity ) {
		super( p_name,p_field_type,p_description,entity );
	}

	public Field newInstance(Entity entity) {
		return new FieldFile(getName(),getFieldType(),getDescription(),entity);
	}

	public void set(File file)
	throws DataException {
		try {
			set(new FileInputStream(file));
		} catch ( Exception exception) {
			throw new DataException(exception);
		}
	}

	public void set(InputStream stream)
	throws SQLException {
		try {
			byte buffer [] = new byte[stream.available()];
			int r = stream.read(buffer);
			setBlob(ByteM.subbyte(buffer,r));
		} catch ( Exception exception) {
			throw new DataException(exception);
		}
	}
	
	public void set(byte data[]) {
		setBlob(data);
	}

	public File get() throws DataException {
		try {
			if (getBlob() != null) {
				File file = File.createTempFile("blueprint4j","tmp");
				FileOutputStream stream = new FileOutputStream(file);
				stream.write(getBlob());
				return file;
			} else {
				return null;
			}
		} catch (Throwable th) {
			throw new DataException(th);
		}
	}
}
